package com.towery.dbsrcmanager.db.service;

import com.towery.dbsrcmanager.db.utils.JdbcUtils;
import com.towery.dbsrcmanager.mybatis.base.entity.TDatabaseVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by User on 2016/12/30.
 */
@Slf4j
public abstract class DatabaseService {

    private TDatabaseVO database ;

    public DatabaseService(TDatabaseVO database){
        this.database =database;
    }
    /**
     * 获取当前报表查询器的JDBC Connection对象
     *
     * @return Connection
     */
    protected Connection getJdbcConnection() {
        try {
            return JdbcUtils.getDataSource(database).getConnection();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
    public List<Map<String,Object>> queryForList(String sqltext) throws Exception {

        List<Map<String,Object>>  result =null;

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;


        try {
            log.debug("Run SQL:{},", sqltext);
            conn = this.getJdbcConnection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sqltext);
            ResultSetMetaData rsMataData = rs.getMetaData();
            int count = rsMataData.getColumnCount();
            List<String> columns = new ArrayList<>(count);
            for (int i = 1; i <= count; i++) {
                columns.add(rsMataData.getColumnLabel(i).toUpperCase());
            }

            result =new ArrayList<Map<String,Object>>();
            while(rs.next()){
                   Map<String,Object> data =new HashMap<String,Object>();
                   for(int i=0;i<count ;i++ ){
                       Object  rsObject= rs.getObject(i+1);
                       if(rsObject instanceof Clob){
                           Reader ir =( (Clob)rsObject).getCharacterStream();
                           String s=StringUtils.join( IOUtils.readLines(ir) , "\n");
                           data.put(columns.get(i), s);
                       }
                       else{
                           data.put(columns.get(i), rsObject);
                       }
                   }
                   result.add(data);
            }


        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        } finally {
            JdbcUtils.releaseJdbcResource(conn, stmt, rs);
        }
        return result;
    }

    public String getSqlSource(String uri) throws IOException {
         return StringUtils.join(  IOUtils.readLines( this.getClass().getResourceAsStream(uri) ,"UTF-8") ," " );
    }
    /*获取对应对象的DDL*/
    public abstract String getTableDDL(String scema, String tablename) throws Exception ;
    /*获取对应对象的DDL(添加表注释)*/
    public abstract String getTableDDL(String scema, String tablename, String tableremark) throws Exception;

    /*取得全部对象*/
    public abstract List<Map<String,Object>> getObjects() throws Exception ;




}
